import {CCard} from '@/components/card'
import {IconImg, ParamOfStatus} from '@/components/image'
import {CnBoldSpan, CnNormalSpan} from '@/components/text'
import CEcharts from '@/components/echarts'
import RollerDigital from '@/components/rollerDigital'
import {PropType} from 'vue'
import dayjs, {Dayjs} from 'dayjs'
import {coustomEchartTooltip, numRound} from '@/libs/toolkit'
import deepClone from '@/libs/deepClone'
import {ECOption} from '@/libs/global/echarts'

export const WaterOverviewCard = defineComponent({
  props: {
    waterOverview: {
      type: Object as PropType<SingleParam.WaterOverview>,
      required: true
    },
    dateTime: {
      type: Array as unknown as PropType<[string, string]>,
      default: () => ['', '']
    },
    spinning: Boolean
  },
  emits: {
    'update:dateTime': (data: [string, string]) => true
  },
  setup(props, {emit}) {
    const state = reactive<{
      activeKey: '1' | '2' | '3'
      date: [Dayjs, Dayjs]
      option: ECOption
    }>({
      activeKey: '1',
      date: [dayjs(), dayjs()],
      option: {
        tooltip: {
          trigger: 'axis',
          className: 'tooltipBox',
          formatter: (params: any) =>
            coustomEchartTooltip(params, {contentLeftTextKey: 'seriesName'})
        },
        grid: {
          left: '5%',
          right: '3%',
          top: '10%',
          bottom: '8%'
        },
        dataZoom: {
          type: 'inside',
          start: 0,
          end: 100,
          disabled: false
        },
        yAxis: {
          type: 'value',
          max: (val: {max: number; min: number}) => {
            let max = numRound(val.max * 0.5 + val.max, 0)
            console.log(max)

            return isNaN(max) ? 10 : max
          },
          min: (val: {max: number; min: number}) => {
            let min = numRound(val.min - val.min * 0.5, 0)
            console.log(min)
            return isNaN(min) ? 10 : min
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#E5E8EF'
            }
          },
          axisLabel: {
            fontSize: '12px',
            color: '#bfbfbf'
          }
        },
        animation: true,
        animationDuration: 3000
      }
    })

    const optionXAxis: ECOption = {
      xAxis: {
        type: 'category',
        data: [],
        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: '#BFBFBF'
          }
        },
        axisLabel: {
          formatter(value: string, index: number) {
            console.log(value, index)

            return dayjs(value).format('M月D')
          },
          fontSize: '12px',
          fontWeight: 500,
          fontFamily: 'Source Han Sans CN-Medium, Source Han Sans CN',
          color: '#31456A'
        }
      }
    }
    const optionLegend: ECOption = {
      legend: {
        data: [],
        right: 10,
        top: 0,
        itemHeight: 6,
        textStyle: {
          fontSize: 12,
          color: '#293035'
        }
      }
    }
    const optionsSeries: ECOption = {
      series: [
        {
          zlevel: 0,
          z: 0,
          name: '',
          data: [],
          type: 'line',
          showSymbol: false,
          symbolSize: 12,
          lineStyle: {
            width: 3,
            color: '#1758F0'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: '#CDF0FF' // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: '#fff' // 100% 处的颜色
                }
              ],
              global: false // 缺省为 false
            }
          }
        }
      ]
    }

    watch(
      () => state.activeKey,
      n => {
        switch (n) {
          case '1':
            state.date = [dayjs(), dayjs()]
            break
          case '2':
            state.date = [dayjs().subtract(1, 'week'), dayjs()]
            break
          case '3':
            state.date = [dayjs().subtract(1, 'month'), dayjs()]
            break
          default:
            state.date = [dayjs().subtract(1, 'month'), dayjs()]
            break
        }
      }
    )

    watch(
      () => state.date,
      n => {
        emit('update:dateTime', [
          n[0].format('YYYY-MM-DD 00:00:00'),
          n[1].format('YYYY-MM-DD 23:59:59')
        ])
      },
      {immediate: true}
    )

    watch(
      () => props.waterOverview,
      n => {
        const option = deepClone(state.option) as ECOption
        const xAxisData = n.checkDataList.map(item => item.checkTime)
        // @ts-ignore
        optionXAxis.xAxis.data = xAxisData
        // @ts-ignore
        optionsSeries.series[0].data = n.checkDataList.map(item => Number(item.checkDataValue || 0))
        // @ts-ignore
        optionsSeries.series[0].name = n.checkData.checkDataName
        // @ts-ignore
        optionLegend.legend.data = [n.checkData.checkDataName]

        option.xAxis = optionXAxis.xAxis
        option.series = optionsSeries.series
        option.legend = optionLegend.legend
        state.option = option
      },
      {immediate: true}
    )

    watch(
      () => state.option,
      n => {
        console.log(n)
      },
      {deep: true}
    )

    return () => (
      <div class='col-span-2 row-span-2'>
        <a-spin spinning={props.spinning}>
          <CCard
            class='bg-white rounded-4'
            title={`水质总览,${props.waterOverview.checkData.checkDataName}`}
            v-slots={{
              title: () => (
                <div class='w-full flex justify-between items-center'>
                  <div>
                    <CnBoldSpan>{props.waterOverview.checkData.checkDataName}</CnBoldSpan>
                    <CnNormalSpan class='text-16 font-normal ml-15'>
                      {props.waterOverview?.devName || ''}
                    </CnNormalSpan>
                  </div>
                  <span class='inline-flex items-center'>
                    <IconImg class='w-14 h-14 mr-8' imgName='calendar'></IconImg>
                    <CnBoldSpan class='text-text text-13'>近一月</CnBoldSpan>
                  </span>
                </div>
              )
            }}
          >
            <div class='w-full h-46 mt-22 flex justify-between pl-4 pr-8'>
              <div class='h-full flex items-end flex-1'>
                <RollerDigital
                  class='h-full text-32 text-text pt-7'
                  endVal={Number(props.waterOverview.checkData.checkDataValue || 0)}
                  decimals={2}
                ></RollerDigital>
                {props.waterOverview.checkData.checkDataUnit ? (
                  <CnNormalSpan class='ml-20'>
                    {props.waterOverview.checkData.checkDataUnit}
                  </CnNormalSpan>
                ) : null}
                <ParamOfStatus
                  class='ml-40 h-21'
                  status={props.waterOverview.checkData.paramStatus}
                >
                  {props.waterOverview.checkData.paramStatus}
                </ParamOfStatus>
                <div class='ml-12'>
                  <CnNormalSpan class='mr-8 text-12'>合格标准:</CnNormalSpan>
                  <CnNormalSpan class='text-12'>
                    {props.waterOverview.checkData.checkDataDesc || (
                      <CnNormalSpan class='text-warning'>暂未设置合格标准</CnNormalSpan>
                    )}
                  </CnNormalSpan>
                </div>
              </div>
              <CnNormalSpan class='text-12 text-5xText'>
                最近更新时间: {props.waterOverview.checkData.checkTime}
              </CnNormalSpan>
            </div>

            <div class='w-full mt-20'>
              <div class='w-full h-30 flex justify-between items-center'>
                <div>
                  <CnNormalSpan class='text-text mr-10'>水质趋势</CnNormalSpan>
                  <CnNormalSpan class='text-danger'>
                    异常指标 &lt; {props.waterOverview.exceptionRatio}%
                  </CnNormalSpan>
                </div>
                <div class='h-full flex items-center'>
                  <a-range-picker
                    v-model={[state.date, 'value']}
                    class='mr-32'
                    allowClear={false}
                  ></a-range-picker>

                  <a-tabs class=' h-full mr-32 pb-6' v-model={[state.activeKey, 'activeKey']}>
                    <a-tab-pane
                      key='1'
                      tab={() => (
                        <CnNormalSpan class={[' ', state.activeKey === '1' ? 'text-xText' : '']}>
                          日
                        </CnNormalSpan>
                      )}
                    ></a-tab-pane>
                    <a-tab-pane
                      key='2'
                      tab={() => (
                        <CnNormalSpan class={[' ', state.activeKey === '2' ? 'text-xText' : '']}>
                          周
                        </CnNormalSpan>
                      )}
                    ></a-tab-pane>
                    <a-tab-pane
                      key='3'
                      tab={() => (
                        <CnNormalSpan class={[' ', state.activeKey === '3' ? 'text-xText' : '']}>
                          月
                        </CnNormalSpan>
                      )}
                    ></a-tab-pane>
                  </a-tabs>
                </div>
              </div>

              <div class='w-full'>
                <div class='w-full h-32'></div>
                <div class='w-full'>
                  {
                    <CEcharts
                      id='waterOverview-lineEchart'
                      width={'100%'}
                      height={'260px'}
                      option={state.option as ECOption}
                    ></CEcharts>
                  }
                </div>
              </div>
            </div>
          </CCard>
        </a-spin>
      </div>
    )
  }
})
